package com.iqiyi.util;


import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

/**
 *
 *  redis序列化工具
 * @author YoungKai
 * @date 2021/2/11 18:33
 */
public class RedisUtilSerializer implements RedisSerializer<Object> {

    //获取序列化的转换器
    Converter<Object,byte[]> serializingConverter = new SerializingConverter();
    //获取反序列化转化器
    Converter<byte[],Object> deserializingConverter = new DeserializingConverter();
    private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
    //对象序列化
    @Override
    public byte[] serialize(Object o) throws SerializationException {
        if (o==null){
            return EMPTY_BYTE_ARRAY;
        }else{
            byte[] convert = serializingConverter.convert(o);
            return convert;
        }
    }

    //反序列化
    @Override
    public Object deserialize(byte[] bytes) throws SerializationException {
        if (bytes != null){
            return deserializingConverter.convert(bytes);
        }
        return null;
    }
}
